<?php
/*
 * hazg.net 2008
 */
	class Web 
	{
		const GET_TYPE_PHP = 0;
		const GET_TYPE_SPY = 1; 
		const GET_FILE_ALL = 0;
		const GET_FILE_BODY = 1;
		//const GET_FILE_HEADER = 2;
		static function Get($url, $post = null, $get_type = Web::GET_TYPE_SPY, $get_file = Web::GET_FILE_BODY) 
		{
			if($get_type = Web::GET_TYPE_PHP)
				return file_get_contents($url);
			return Web::SendHeader($url, Web::GetHeader($url, $post), $get_file);
		}
				
		static function SendHeader($host, $head, $get_file)
		{
			$p_url = parse_url($host);
			$fp = fsockopen($p_url['host'], 80, $errno, $errstr, 20);
			fwrite($fp, $head, strlen($head));
			$response = '';			 
			while(false !== ($buf = fgets($fp)))
			{
				$response.=$buf;
			}
			/*Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
set-cookie: session=5F3F5D4E09E05454; expires=Wed, 22 Oct 2008 11:03:32 GMT; path=/
Content-Encoding: gzip*/
			$headerPos = stripos($response, chr(0x0D).chr(0x0A).chr(0x0D).chr(0x0A));
			$header = substr($response, 0, $headerPos);
			$body = substr($response, $headerPos+4);
			//TODO: Content-Type iconv
			unset($response);
			if(preg_match('#.*Content-Encoding:\sgzip.*#is', $header))
				$body = gzinflate(substr($body,2));
			
					
			 
			fclose($fp);
			
			if($get_file === Web::GET_FILE_ALL)
	    		return $header.chr(0x0D).chr(0x0A).chr(0x0D).chr(0x0A).$body;
	    	else if($get_file === Web::GET_FILE_BODY)
	    		return $body;
		}
		static function GetHeader($url, $post)
		{
			$p_url = parse_url($url);
			$q = (array_key_exists('query', $p_url)?("?".$p_url['query']):'');
			if($post == null)
			{
				$u = str_replace(' ', '%20', $p_url['path']);
				//print 'TEST: '.urlencode();
				$header = "GET ".$u.$q." HTTP/1.1\r\n";
				$header .= "Accept: */*\r\n";
				$header .= "Accept-Language: ru\r\n";
				//$header .= "Accept-Encoding: gzip, deflate\r\n";
				$header .= "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)\r\n";
				$header .= "Host: ".$p_url['host']."\r\n";
				//$header .= "Connection: Keep-Alive\r\n";
				$header .= "Connection: Close\r\n\r\n";
			}
			else 
			{
				$query = http_build_query($post);
				$u = str_replace(' ', '%20', $p_url['path']);
				$header = "POST ".$u.$q." HTTP/1.1\r\n". 
				"Host: ".$p_url['host']."\r\n".
				"User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)\r\n". 
				"Content-Type: application/x-www-form-urlencoded\r\n".
				"Connection: Close\r\n". 
				"Content-Length: ".strlen($query)."\r\n\r\n". 
				"$query\r\n";
			}
			return $header;
		}
	}
	
?>